#include "utils.h"

static char escaped_chrs[] = "$&+,/:;=?@ \"<>#%{}|\\^~[]`'";

static int is_special_char(char c)
{
    int i = 0;

    if (c < 32 || c > 122) {
        return TRUE;
    }
    else {
        while (escaped_chrs[i]) {
            if (c == escaped_chrs[i]) {
                return TRUE;
            }
            ++i;
        }
    }

    return FALSE;
}

char* s3_escape_url(const char *in, apr_pool_t *pool)
{
    int i = 0;
    int ni = 0;
    char *out;

    /* Count the number of replacements */
    while (in[i]) {
        if (is_special_char(in[i])) {
            ni++;
        }
        ++ni;
        ++i;
    }

    /* Allocate the buffer */
    out = apr_palloc(pool, ni + 1);

    
    /* Perform the copy + replacement */
    ni = i = 0;
    while (in[i]) {
        if (in[i] == ' ') {
            out[ni++] = '+';
            i++;
        }
        else {
            if (is_special_char(in[i])) {
                out[ni++] = '%';
                out[ni++] = "0123456789ABCDEF"[in[i] / 16];
                out[ni++] = "0123456789ABCDEF"[in[i] % 16];
                ++i;
            }
            else {
                out[ni++] = in[i++];
            }
        }
    }
    
    out[ni] = '\0';

    return out;
}

